package rad.framework.mda.jpagen.actions;

import rad.framework.mda.generator.Console;
import rad.framework.mda.generator.util.StereotypeHelper;
import rad.framework.mda.util.ModelUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;

/**
 * @author boudyacho
 * 
 */
public class AddJoinColumnActionExtension extends BaseUtiltiyActionExtension {

	protected static final String JOIN_COLUMN = "javax.persistence.JoinColumn";

	public void fillContextMenu(IMenuManager aMenu) {
		getSubMenu(aMenu).add(new AddJoinColumnAction());
	}

	protected void execute(Class clazz) {
		if (StereotypeHelper
				.isStereotypeApplied(clazz, StereotypeHelper.ENTITY)) {
			EList<NamedElement> list = clazz.getMembers();
			for (NamedElement namedElement : list) {
				if (namedElement instanceof Property) {
					execute((Property) namedElement);
				}
			}
		}
	}

	protected void execute(Property property) {
		if (ModelUtil.isStereotypeApplied(property, M2O)
				|| ModelUtil.isStereotypeApplied(property, O2O)) {
			applyJoinColumn(property);
			Console.getStream().println(
					"Added " + JOIN_COLUMN + " - "
							+ property.getQualifiedName());
		}
	}

	private void applyJoinColumn(Property element) {
		Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
				element, JOIN_COLUMN);
		if (stereotype != null) {
			if (!ModelUtil.isStereotypeApplied(element, JOIN_COLUMN)) {
				element.applyStereotype(stereotype);
			}
			element.setValue(stereotype, "name", NameUtil
					.getAbbreviation(element)
					+ "_ID");
		}
	}

	private class AddJoinColumnAction extends BaseUtilityAction {
		private static final String LABEL = "Add Join Column Stereotypes";

		public AddJoinColumnAction() {
			super(LABEL);
		}
	}
}
